#ifndef _Encoder_H__
#define _Encoder_H__
#include "os/os.h"
#include "controller/pll.h"
#include "bsp/enc_hw_intf.h"

typedef struct {
	bool  b_pos_sync; //通过pwm信号同步timer count
	bool  b_inited;
	float enc_offset;
	u32   abi_pwm_count;
	u8    motor_poles;
	float pwm_angle;
	float pwm_count;
	float abi_angle;
	float cali_angle;
	float interpolation;
	float pll_bandwidth_shadow;
	float pll_bandwidth;
	float pll_max_bandwith;
	float pll_min_bandwith;
	float omega_for_max_bandwith;
	float position;
	pll_t pll;
	bool  b_overflow;
	bool  b_lock_pos;
	float cpr;
	float last_cnt;
	u32   last_us;
	s8    direction; //motor running dir, 逆时针 正，顺时针负
	float velocity; 
	float velocity_filted; 
	float est_vel_cnt_filted;
	float est_angle_counts;
	float est_elec_w_filted;
	u8    enc_maybe_err;
	u32   pwm_errors;
	u32   init_time;
	os_timer_t check_timer;
}mag_encoder_t;

#define ENCODER_NO_ERR 0
#define ENCODER_PWM_ERR 1
#define ENCODER_AB_ERR  2

void encoder_init(mag_encoder_t *enc);
float encoder_update_elec_angle(mag_encoder_t *enc);
void encoder_enable_pos_lock(mag_encoder_t *enc, bool en);
float encoder_get_velocity(mag_encoder_t *enc);
float encoder_get_elec_angle(mag_encoder_t *enc);
float encoder_get_abs_angle(mag_encoder_t *enc);
float encoder_get_abi_angle(mag_encoder_t *enc);
float encoder_get_position(mag_encoder_t *enc);
void encoder_set_direction(mag_encoder_t *enc, s8 direction);
bool encoder_have_error(mag_encoder_t *enc);
u8 encoder_may_error(mag_encoder_t *enc);
bool encoder_align_position(mag_encoder_t *enc, float pos);
bool encoder_is_ready(mag_encoder_t *enc);
void encoder_abi_irq_handler(mag_encoder_t *enc, u32 count);
void encoder_log(mag_encoder_t *enc);
#endif /* _Encoder_H__ */

